import { Component } from '@angular/core';
import {ActionSheetController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {InfoProvider} from "../../providers/InfoProvider";
import {ImageProvider} from "../../providers/ImageProvider";
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import {HttpService} from "../../providers/HttpService";
import {CommProvider} from "../../providers/CommProvider";

/**
 * Generated class for the PubDiscoveryPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-pub-discovery',
  templateUrl: 'pub-discovery.html',
})
export class PubDiscoveryPage {

  placeholder: string = 'assets/img/news-image-temp.jpg';
  chosenImage: string = null;

  post_data: any = {
    admin_id: null,
    content: null,
    image: null
  };

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private infoProvider: InfoProvider,
              private commProvider: CommProvider,
              private imageProvider: ImageProvider,
              private httpService: HttpService,
              private transfer: FileTransfer,
              private file: File,
              private actionSheetCtrl: ActionSheetController) {
      let user_data = this.infoProvider.getUserInfo();
      this.post_data.admin_id = user_data.id;
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad PubDiscoveryPage');
  }

  onImageUpload() {
    const actionSheet = this.actionSheetCtrl.create({
      title: '选择图片',
      buttons: [
        {
          text: '相册',
          icon: !this.infoProvider.isIos() ? 'image' : null,
          handler: () => {
            this.getPicture();
          }
        },
        {
          text: '拍照',
          icon: !this.infoProvider.isIos() ? 'camera' : null,
          handler: () => {
            this.takePicture();
          }
        }
      ]
    });
    actionSheet.present();
  }

  takePicture() {
    return this.imageProvider.getPictureFromCamera().then(picture => {
      if (picture) {
        this.uploadImage(picture);
      }
    }, error => {
      this.commProvider.showToast(error);
    });
  }

  getPicture() {
    return this.imageProvider.getPictureFromPhotoLibrary().then(picture => {
      if (picture) {
        this.uploadImage(picture);
      }
    }, error => {
      this.commProvider.showToast(error);
    });
  }

  uploadImage(filePath : string) {
    let options: FileUploadOptions = {
      headers: {authorization : HttpService.getAuthPrimary()}
    };
    const fileTransfer: FileTransferObject = this.transfer.create();
    let uploadApi = HttpService.getImageUrl('/image/biz/imageUpload');
    fileTransfer.upload(filePath, uploadApi, options)
      .then((data) => {
        let result = JSON.parse(data.response);
        if (result.status == 0) {
          this.chosenImage = HttpService.getImageLink(result.data.image);
          this.post_data.image = result.data.image;
        } else {
          this.commProvider.showToast(result.msg);
        }
      }, (err) => {
        if (err.body) {
          let errBody = JSON.parse(err.body);
          this.commProvider.showToast(errBody.msg);
        } else {
          this.commProvider.showToast('图片上传失败');
        }
      });
  }

  onPubDiscovery() {
    if (this.post_data.image || this.post_data.content) {
      this.httpService.instance()
        .setUrl('/dailyShare/addDailyShare')
        .setBody(this.post_data)
        .postRequest()
        .then(res => {
          if (res.status == 0) {
            this.navCtrl.pop();
          }
        });
    } else {
      this.commProvider.showToast('请添加分享内容');
    }
  }
}
